#include "StdAfx.h"
#include "BufReader.h"

#ifdef _DEBUG
#include "crtdbg.h"
#endif

#define FILE_BUF_LEN 4096

bool CBufReader::ReadLine(CString& s)
{
  if (m_pData == NULL || m_lPos >= m_lSize)
    return false;

  static char     buf[FILE_BUF_LEN];
  static wchar_t  wbuf[FILE_BUF_LEN];

  long eol = m_lPos;
  for (; eol <= m_lSize; eol++)
    if (eol == m_lSize || (m_pData[eol] == '\r' && m_pData[eol+1] == '\n'))
      break;

  long size = eol - m_lPos;
  if (size == 0)
    return false;
  if (size > FILE_BUF_LEN - 1)
    size = FILE_BUF_LEN - 1;
  ::CopyMemory(buf, m_pData + m_lPos, size * sizeof(BYTE));
  buf[size] = 0;
  m_lPos = eol;

  // strip newline
  size_t len = strlen(buf);
  if (len)
  {
    // convert to Unicode
    ::MultiByteToWideChar(m_bUtf8 ? CP_UTF8 : CP_ACP, 0,
                          buf, -1, wbuf, FILE_BUF_LEN);
    // copy result
    s = wbuf;
  }
  else
  {
    s.Empty();
  }

  m_nLine++;
  return true;
}

void CBufReader::DetectUtf8()
{
  if (m_pData == NULL)
    return;

  BYTE bom[3]  = { 0xEF, 0xBB, 0xBF };
  long len = sizeof(bom) / sizeof(bom[0]);
  if (m_lSize >= len && ::memcmp(bom, m_pData, len) == 0)
  { // is BOM
    m_bUtf8 = true;
    m_lPos += len;
  }
  else
  { // no BOM
    m_bUtf8 = false;
  }
}